function extractDataMain()

rootDir='/Users/matthew/workspace/data/mImaginery/eegmmidb/';
outDir='/Users/matthew/workspace/data/mImaginery/data/';

filter='S1*'
subjNames=dir(fullfile(rootDir,filter));

task1={'R03','R07','R11'};
task2={'R04','R08','R12'};
events=[2 3 4];
eventLabelTask1={'_Rrest','_Rleft','_Rright'};
eventLabelTask2={'_Irest','_Ileft','_Iright'};

for i=1:length(subjNames)
    extractData(rootDir,outDir,subjNames(i).name,task1,events,eventLabelTask1)
    extractData(rootDir,outDir,subjNames(i).name,task2,events,eventLabelTask2)
end

function extractData(rootDir,outDir,subjName,task,events,eventLabels)

% rootDir='/Users/matthew/workspace/data/mImaginery/';
% outDir='/Users/matthew/workspace/mfiles/projects/real&imaginery/';
% subjName='S001';
% task={'R03','R07','R11'};
% restEvent=2;
% leftEvent=3;
% rightEvent=4;
% events=[restEvent,leftEvent,rightEvent];
% eventLabels={'_rrest','_rleft','_rright'}
% outDir='/Users/matthew/workspace/mfiles/projects/real&imaginery';

fileNames=fileNames2Merge(subjName,task);
extractTaskTrials(rootDir,subjName,fileNames,outDir,events,eventLabels);

function extractTaskTrials(rootDir,subjName,fileNames,outDir,events,eventLabels)

for i=1:length(fileNames)
    filename=fullfile(strcat(rootDir,subjName),fileNames{i});
    edfData(i)=readEDFplus(filename);
end

for i=1:length(events)
    for j=1:length(edfData)
        dataV(j)=defineTrials(edfData(j),events(i));
    end    
    data=mergeTrials(dataV);
    outfile=strcat(subjName,eventLabels{i});
    save(fullfile(outDir,outfile),'data')   
end


function [fileNames]=fileNames2Merge(subjName,runNames)

fileNames=strcat(strcat(subjName,runNames),'.edf');

function [data]=mergeTrials(toMerge)
data=toMerge(1);
for i=2:length(toMerge)
    data=merge2Trials(data,toMerge(i));
end

function [dataout]=merge2Trials(data1,data2)

%check same labels and fsample
if(all(strcmp(data1.label,data2.label)) && data1.fsample==data2.fsample)
    dataout.label=data1.label;
    dataout.fsample=data1.fsample;
    dataout.trial=cat(2,data1.trial,data2.trial);
    dataout.time=cat(2,data1.time,data2.time);
else
    error('Channels or sample rate between data1 and data2 are different')
end